package com.qriver.session.interceptor;

import com.qriver.session.common.CommonResult;
import com.qriver.session.common.SsoConstant;
import com.qriver.session.facade.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token 拦截器
 */
public class CookieTokenInterceptor implements HandlerInterceptor {

    @Value("${sso.login}")
    private String ssoLoginUrl;

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //1、通过session验证是否已登录
        String user = (String) request.getSession().getAttribute("user");
        //第一次登录或登录失效时，跳转到SSO登录界面
        if(StringUtils.isEmpty(user)){
            //获取临时票据，并验证
            String tmpTicket = request.getParameter("tmpTicket");
            if(StringUtils.isEmpty(tmpTicket)){//没有临时票据，则跳转到SSO登录界面
                //记录访问当前路径
                modelAndView.addObject(SsoConstant.REDIRECT_URL, request.getRequestURL());
                //跳转到SSO登录界面
                modelAndView.setViewName("redirect:" + ssoLoginUrl);
            }else{//存在临时票据，验证是否有效
                CommonResult result = tokenService.verifyTmpTicket(tmpTicket);
                if(result.getStatus() != 200){//验证不通过，跳转登录界面
                    //记录访问当前路径
                    modelAndView.addObject(SsoConstant.REDIRECT_URL, request.getRequestURL());
                    //跳转到SSO登录界面
                    modelAndView.setViewName("redirect:" + ssoLoginUrl);
                }else{//验证通过，在该微服务中记录登录状态，即保存session信息
                    String userInfo = (String) result.getData();
                    request.getSession().setAttribute("user",userInfo);
                    //跳转到当前页面
                   // String redirectUrl = request.getParameter(SsoConstant.REDIRECT_URL);
                   // modelAndView.setViewName("redirect:" + redirectUrl);
                }
            }
        }else{//验证user信息是否过期

        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
